package com.pig.common;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

/**
 * @author by 李志伟
 * Create Date: 2019/1/7 13:31
 * Description:
 */
public class JsonUtils {
    /**
     * 把bean，转为json
     *
     * @param obj
     * @return
     */
    public static String objToJsonStr(Object obj) {
        Gson gson = new Gson();
        String toJson = gson.toJson(obj);
        return toJson;
    }

    /**
     * 把json字符串转换为对象
     *
     * @param jsonStr
     * @param clazz
     * @return
     */
    public static <T> T jsonStrToBean(String jsonStr, Class<T> clazz) {
        Gson gson = new Gson();
        Type type = TypeToken.get(clazz).getType();
        return (T) gson.fromJson(jsonStr, type);
    }
    public static <T> T jsonStrToBean(String jsonStr,Type type) {
        Gson gson = new Gson();
        return (T) gson.fromJson(jsonStr, type);
    }
}
